package com.xhtt.modules.task.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xhtt.modules.cfg.entity.CfgComprod;
import com.xhtt.modules.cfg.entity.CfgStand;
import com.xhtt.modules.cfg.service.CfgComprodService;
import com.xhtt.modules.cfg.service.CfgStandService;
import com.xhtt.modules.task.dao.TruckInfoMapper;
import com.xhtt.modules.task.entity.TaskCarPlan;
import com.xhtt.modules.task.entity.TaskCarTask;
import com.xhtt.modules.task.entity.TruckInfo;
import com.xhtt.modules.task.service.TaskCarPlanService;
import com.xhtt.modules.task.service.TaskCarTaskService;
import com.xhtt.modules.task.service.TruckInfoService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author feipc
 * @since 2019-05-14
 */
@Service
public class TruckInfoServiceImpl extends ServiceImpl<TruckInfoMapper, TruckInfo> implements TruckInfoService {

    @Autowired
    private TruckInfoService truckInfoService;
    @Autowired
    private TaskCarPlanService taskCarPlanService;
    @Autowired
    private TaskCarTaskService taskCarTaskService;
    @Autowired
    private CfgStandService standService;
    @Autowired
    private CfgComprodService comprodService;
    @Resource
    private TransactionTemplate transactionTemplate;

    @Override
    public void getDataFromTAS(String wiNewTime) {
        List<TruckInfo> list = baseMapper.getData(wiNewTime);

        if (CollectionUtils.isNotEmpty(list)) {
            //写入到我们的库,做备份
            truckInfoService.saveOrUpdateBatch(list, 1000);

            //获取已有的装车台 和产品
            List<CfgStand> standList = standService.list();
            Map<String, Integer> standMap = new HashMap<>();
            standList.forEach(sd -> standMap.put(sd.getName(), sd.getId()));

            List<CfgComprod> productList = comprodService.list(new LambdaQueryWrapper<CfgComprod>().ne(CfgComprod::getStatus, -1));
            Map<String, Integer> productMap = new HashMap<>();
            productList.forEach(pd -> productMap.put(pd.getName(), pd.getId()));

            //解析到业务库
            //获取已经存在的数据，seriaNo唯一，就以这个字段为标准
            Set<Integer> sids = list.stream().map(truckInfo -> truckInfo.getActivityNo()).collect(Collectors.toSet());
            List<TaskCarPlan> dbCarPlanList = taskCarPlanService.list(new LambdaQueryWrapper<TaskCarPlan>().notIn(TaskCarPlan::getActivityNo, sids).select(TaskCarPlan::getSerialNo, TaskCarPlan::getId));
            Map<String, Integer> seriaNoIdMap = new HashMap<>();
            dbCarPlanList.forEach(cp -> seriaNoIdMap.put(cp.getSerialNo(), cp.getId()));
            TaskCarPlan taskCarPlan;
            for (TruckInfo ti : list) {
                try {
                    Integer seriaNo = ti.getActivityNo();
                    taskCarPlan = new TaskCarPlan();
                    taskCarPlan.setSerialNo(seriaNo.toString());//他们没有流水号 ，就用唯一的订单号吧
                    taskCarPlan.setActivityNo(seriaNo);//订单号
                    taskCarPlan.setCarNo(ti.getCallName());//车牌
                    taskCarPlan.setNumber(String.valueOf(ti.getNomQty()));//数量
                    taskCarPlan.setDateInvoice(ti.getCreateDate());//开票时间
                    taskCarPlan.setDateRegister(ti.getCreateDate());//门卫登记时间，他们没有所以就共用开票时间
                    taskCarPlan.setDateWeigh(ti.getWiNewTime());//空车过磅时间
                    taskCarPlan.setPotNo(ti.getTank());//罐号 没验证是否存在，因为系统没做关联直接存的号
                    if (null == productMap.get(ti.getProduct())) {//产品
                        ti.setErrorInfo("产品不存在");
                        truckInfoService.updateById(ti);
                        continue;
                    } else {
                        taskCarPlan.setProductId(productMap.get(ti.getProduct()));
                        taskCarPlan.setProductName(ti.getProduct());
                    }
                    if (null == standMap.get(ti.getBay())) {//台
                        ti.setErrorInfo("装车台不存在");
                        truckInfoService.updateById(ti);
                        continue;
                    } else {
                        taskCarPlan.setStageId(standMap.get(ti.getBay()));
                    }
//                        ti.setErrorInfo("OK");//需要记录下操作结果吗？需要的话就打开
//                        truckInfoService.updateById(ti);
                    if (seriaNoIdMap.containsKey(seriaNo.toString())) {
                        taskCarPlan.setId(seriaNoIdMap.get(seriaNo.toString()));
                        taskCarPlanService.updateById(taskCarPlan);
                    } else {
                        TaskCarPlan finalTaskCarPlan = taskCarPlan;
                        transactionTemplate.execute(transactionStatus -> {
                            try {
                                taskCarPlanService.save(finalTaskCarPlan);
                                TaskCarTask task = new TaskCarTask();
                                task.setCarPlanId(finalTaskCarPlan.getId());
                                taskCarTaskService.save(task);
                                seriaNoIdMap.put(seriaNo.toString(), finalTaskCarPlan.getId());
                            } catch (Throwable e) {
                                e.printStackTrace();
                                transactionStatus.setRollbackOnly();
                            }
                            return null;
                        });

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }

            }

        }


    }

    @Override
    public String getMaxDate() {
        return baseMapper.getMaxDate();
    }

    @Override
    public String getMaxPrintDate() {
        return baseMapper.getMaxPrintDate();
    }

    @Override
    public void getPrintDataFromTAS(String maxPrintDate) {
        List<TruckInfo> list = baseMapper.getPrintData(maxPrintDate);

        if (CollectionUtils.isNotEmpty(list)) {
            //更新到我们的库,做备份
            truckInfoService.updateBatchById(list, 1000);
            //解析到业务库
            for (TruckInfo ti : list) {
                try {
                    Integer seriaNo = ti.getActivityNo();
                    if (null != seriaNo) {
                        TaskCarPlan plan = taskCarPlanService.getOne(new LambdaQueryWrapper<TaskCarPlan>().eq(TaskCarPlan::getActivityNo, seriaNo).select(TaskCarPlan::getId));
                        if (null != plan && null != plan.getId()) {
                            taskCarTaskService.update(new TaskCarTask(), new UpdateWrapper<TaskCarTask>().set(TaskCarTask.HeavyWeighDate, ti.getWoNewTime()).set(TaskCarTask.PrintDate, ti.getUploadDate()).eq(TaskCarTask.CarPlanId, plan.getId()));
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }

            }

        }
    }
}
